package com.tcpengine.handler;

import java.io.ObjectInputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.tcpengine.dao.UserInfo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;

// 业务处理过程
public class GameProcess extends Thread { 
	private List<NetPackage> packList = new LinkedList<NetPackage>();
	
	
	void addPack(NetPackage pack) {
		packList.add(pack);
	}
	
	// 发送消息
	private void sendBinMessage(Channel ch, ByteBuf byteBuf, int netType) {
		if(NetPackage.WS_TYPE == netType) {
			BinaryWebSocketFrame binFrame = new BinaryWebSocketFrame(byteBuf);
			ch.writeAndFlush(binFrame).addListener(new ChannelFutureListener() {
				public void operationComplete(ChannelFuture channelFuture) throws Exception {
					if (channelFuture.isSuccess()) {
						System.out.println("websocket发送消息成功");
					} else {
						System.out.println("websocket消息发送失败 " + channelFuture.cause().getMessage());
					}
				}
			});
		}
		else {
			ch.writeAndFlush(byteBuf).addListener(new ChannelFutureListener() {
				public void operationComplete(ChannelFuture channelFuture) throws Exception {
					if (channelFuture.isSuccess()) {
						System.out.println("tcp发送消息成功");
					} else {
						System.out.println("tcp消息发送失败 " + channelFuture.cause().getMessage());
					}
				}
			});
		}
		
		
		
		
		
	}
	
	@Override
    public void run() {
		while(true) {
			if(packList.isEmpty()) {
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
					return;
				}
				continue;
			}
			NetPackage netPack = packList.remove(0);
			
			// 网络数据处理
			if(1000 == netPack.msg.id) {	// 消息返回给客户端
				try {
					int loginId = netPack.msg.body.readInt();
					byte[] byPassword = new byte[netPack.msg.bodyLen - 4];
					netPack.msg.body.readBytes(byPassword);
					String loginPwd = new String(byPassword, StandardCharsets.UTF_8);
					
					String strMsg = "收到客户端登陆消息 : " + netPack.msg.id + " 消息体长度是: " + netPack.msg.bodyLen +  
							" 登陆ID是: " + loginId + " 登陆密码是: " + loginPwd;
					System.out.println(strMsg);
					String strSend = "您好，收到了您的登陆信息，登陆ID是: " + loginId + " 登陆密码是: " + loginPwd;
					byte[] bySend = strSend.getBytes("UTF-8");
					ByteBuf bufSend = Unpooled.buffer(bySend.length);
					bufSend.writeBytes(bySend);
					Msg msg = new Msg(netPack.msg.id, bySend.length, bufSend);
					sendBinMessage(netPack.ch, Encoder.encode(msg), netPack.netType);
					System.out.println("发送响应登陆消息");
					
				} catch (Exception e) {
					//e.printStackTrace();
					System.out.println("读取登陆消息体失败: " + e.getMessage());
				}
			}
			else if(1001 == netPack.msg.id) {	// 返回数据结构示例
				System.out.println("收到1001查询用户信息消息");
				UserInfo userInfo = new UserInfo("名字是字符串", 1121, 145.23f, (long)12877087, (byte)1, (short)34);
				UserInfo userInfo2 = new UserInfo("名字是字符串2", 1122, 145.23f, (long)12877087, (byte)1, (short)34);
				UserInfo userInfo3 = new UserInfo("名字是字符串3", 1123, 145.23f, (long)12877087, (byte)1, (short)34);
				
				ByteBuf bufSend;
				try {
					bufSend = userInfo.toByteBuf();
					ByteBuf bufSend2 = userInfo2.toByteBuf();
					ByteBuf bufSend3 = userInfo3.toByteBuf();
					int sendLen = userInfo.sizeof() + userInfo2.sizeof() + userInfo3.sizeof();
					ByteBuf bufBody = Unpooled.buffer(sendLen);
					bufBody.writeBytes(bufSend);
					bufBody.writeBytes(bufSend2);
					bufBody.writeBytes(bufSend3);
					Msg msg = new Msg(netPack.msg.id, sendLen, bufBody);
					sendBinMessage(netPack.ch, Encoder.encode(msg), netPack.netType);
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			else if(1002 == netPack.msg.id) {
				
				byte[] bybody = new byte[netPack.msg.bodyLen];
				netPack.msg.body.readBytes(bybody);
				String strBody = new String(bybody);
				
				String strMsg = "收到客户端登陆消息 : " + netPack.msg.id + " 消息体长度是: " + netPack.msg.bodyLen +  
						"消息体是: " + bybody;
				System.out.println(strMsg);
				String strSend = "您好，收到了您的id=1002消息，消息体是" + strBody;
				byte[] bySend;
				try {
					bySend = strSend.getBytes("UTF-8");
					
					ByteBuf bufSend = Unpooled.buffer(bySend.length);
					bufSend.writeBytes(bySend);
					Msg msg = new Msg(netPack.msg.id, bySend.length, bufSend);
					sendBinMessage(netPack.ch, Encoder.encode(msg), netPack.netType);
					System.out.println("发送响应登陆消息");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				
			}
			
			
			
		}
		
	}
}
